<template>
  <div class="users-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input
            v-model="searchForm.userAccount"
            placeholder="请输入用户账号"
          />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchForm.userNickname"
            placeholder="请输入用户昵称"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.userPhone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="userAccount" label="用户账号" />
      <el-table-column prop="userNickname" label="用户昵称" />
      <el-table-column prop="userPhone" label="手机号" />
      <el-table-column label="用户头像" width="100">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.userPicture" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <!-- <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="handleEdit(row)"
          /> -->
          <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="handleDelete(row.userId)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Delete, Edit } from "@element-plus/icons-vue";
// 引入 api 方法
import { getUserService, deleteUserService } from "../api/user.js";

// 用户列表数据
const tableData = ref([]);

// 分页配置
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
});

// 搜索表单
const searchForm = ref({
  userId: null,
  userAccount: null,
  userNickname: null,
  userPhone: null,
  dateRange: [],
});

// 新增/编辑用户对话框
const dialogVisible = ref(false);
const dialogTitle = ref("新增用户");
const userForm = ref({
  id: "",
  username: "",
  nickname: "",
  phone: "",
  avatar: "",
  password: "", // 新增时需要密码
});
const isEdit = ref(false);

// 处理分页变化
const handlePageChange = (val) => {
  pagination.value.currentPage = val;
  loadUsers();
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  loadUsers();
};

// 搜索用户
const handleSearch = () => {
  pagination.value.currentPage = 1;
  loadUsers();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    userId: null,
    userAccount: null,
    userNickname: null,
    userPhone: null,
    dateRange: [],
  };
  handleSearch();
};

// 打开新增用户对话框
const handleAdd = () => {
  dialogTitle.value = "新增用户";
  isEdit.value = false;
  userForm.value = {
    id: "",
    username: "",
    nickname: "",
    phone: "",
    avatar: "",
    password: "",
  };
  dialogVisible.value = true;
};

// 打开编辑用户对话框
const handleEdit = (row) => {
  dialogTitle.value = "编辑用户";
  isEdit.value = true;
  userForm.value = JSON.parse(JSON.stringify(row));
  userForm.value.password = ""; // 编辑时不显示密码
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteUserService(id)
        .then(() => {
          ElMessage.success("删除成功");
          loadUsers();
        })
        .catch((error) => {
          ElMessage.error("删除失败：" + error.message);
        });
    })
    .catch(() => {});
};

/**
 * 用于编辑、新增用户
 */
const submitForm = () => {
  const apiMethod = isEdit.value ? editUser : addUser;
  apiMethod(userForm.value)
    .then(() => {
      ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
      dialogVisible.value = false;
      loadUsers();
    })
    .catch((error) => {
      ElMessage.error(
        (isEdit.value ? "编辑" : "新增") + "失败：" + error.message
      );
    });
};

// 获取用户列表
const loadUsers = async () => {
  const params = {
    userId: searchForm.value.userId,
    userAccount: searchForm.value.userAccount,
    userNickname: searchForm.value.userNickname,
    userPhone: searchForm.value.userPhone,
    startTime: searchForm.value.dateRange[0],
    endTime: searchForm.value.dateRange[1],

    current: pagination.value.current,
    size: pagination.value.size,
    total: pagination.value.total,
  };

  let result = await getUserService(params);
  tableData.value = result.data?.records || [];
  pagination.value.size = result.data?.size || 10;
  pagination.value.current = result.data?.current || 1;
  pagination.value.total = result.data?.total || 0;
};

onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.users-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 美化搜索区域 */
.search-area {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>